package com.iteaj.iot.test.serial;

import com.iteaj.iot.serial.SerialClient;
import com.iteaj.iot.serial.SerialConnectProperties;
import com.iteaj.iot.serial.SerialPortCreator;
import com.iteaj.iot.test.IotTestHandle;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnExpression("${iot.test.serial-start:false}")
public class SerialTestHandle implements IotTestHandle {

    @Override
    public void start() throws Exception {
        System.out.println("------------------------------------------------------ 开始串口测试 ---------------------------------------------");
        String serialPort1 = "com3", serialPort2 = "com4";
        SerialClient com1 = SerialPortCreator.open(new SerialConnectProperties(serialPort1));// 打开串口1
        SerialClient com2 = SerialPortCreator.openByAsync(new SerialConnectProperties(serialPort2), 13, (receivedData, protocol) -> {
            System.out.println("异步读取报文(固定长度13)： - " + new String(receivedData));
        });// 打开串口2


        com2.writeOfSync("hello serial2".getBytes(StandardCharsets.UTF_8), 10000);

        byte[] readMsg = new byte[13];
        com1.readOfSync(readMsg, 10000);
        System.out.println("同步读取报文: - " + new String(readMsg));

        com1.writeOfSync("packetSize 13".getBytes(StandardCharsets.UTF_8), 3000);
        TimeUnit.SECONDS.sleep(1);
        com2.disconnect(true);
        SerialPortCreator.openByAsync(new SerialConnectProperties(serialPort2), "\r".getBytes(), ((receivedData, protocol) -> {
            System.out.println("异步读取报文(分隔符\\r)： - " + new String(receivedData));
        }));
        com1.write("delimiter \\r\r".getBytes(StandardCharsets.UTF_8));

        com1.disconnect(true);
        com2.disconnect(true);
        TimeUnit.SECONDS.sleep(1);
    }

    @Override
    public int getOrder() {
        return 5500;
    }
}
